<template>
	<view class="products" :data-theme="theme">
		<view class="bg_color" style="padding: 24rpx 24rpx;">
			<u-search v-model="keyword" @custom="searchProduct" @search="searchProduct" placeholder="请输入商品名称/关键字"
				actionText="搜索" :actionStyle="{color:'#FFF'}" shape="square" style="flex: none;"></u-search>
		</view>
		<!-- 商品状态 -->
		<tab-bar style="background-color: #FFF;" :tabList="tabList" :tabIndex.sync="currentIndex"></tab-bar>
		<!-- 商品审核，筛选 -->
		<view style="background-color: #fff;">
			<view style="display: flex; justify-content: center;height: 40px;line-height: 40px;text-align: center;">
				<picker model="selector" @change="timeTypeConfirm" range-key="label" :value="timeTypesIndex"
					:range="timeTypeColumns" @cancel="cancelPicker" style="display: flex;justify-content: center;flex: 1;">
					<view style="flex: 1;justify-content: center;display: flex;"
						:style="{color:timeTypeShow?bgColor:null}" @click="timeTypeShow = true">
						<view style="font-size: 14px;margin-right: 6rpx;">上架时间排序</view>
						<u-icon :name="timeTypeShow?'arrow-up-fill':'arrow-down-fill'" size="10"
							:color="timeTypeShow?bgColor:''"></u-icon>
					</view>
				</picker>
				<view style="flex: 1;justify-content: center;display: flex;">
					<view style="font-size: 14px;margin-right: 6rpx;">筛选</view>
					<u-icon name="arrow-down-fill" size="10"></u-icon>
				</view>
			</view>
		</view>
		<swiper v-if="!tabHeaderLoading" class="tab-view" :duration="300" :current.sync="currentIndex">
			<swiper-item class="swiper-item" v-for="(tab, index) in tabList" :key="index" style="display: flex;">
				<scroll-view scroll-y="true" :style="{ 'padding-bottom':'20rpx' }"
					style="height: 100%; overflow: hidden;" @scrolltolower="scrolltolowerFn">
					<swiper-page-product class="swiper-page" :bgColor="bgColor" :tab="tab" ref="tab"
						@toDetails="toDetails" @openMoreSetting="openMoreSetting" @openUpDataSetting="openUpDataSetting"
						@refresh="refresh" @showInfoModal="showInfoModalByParam"
						@closeComuleDate="closeComuleDate"></swiper-page-product>
				</scroll-view>
			</swiper-item>
		</swiper>
		<view style="position: fixed;bottom: 0px;width: 100%;padding: 10px;background-color: #FFF;">
			<button @click="toAddProduct()" style="font-weight: bold;border-radius: 10px;color: #FFF;padding: 20rpx;"
				class="bg_color" :color="bgColor">发布商品</button>
		</view>

		<!-- 更多设置 弹窗 -->
		<tui-drawer mode="bottom" :visible="moreSettingDrawer" @close="closeMoreSetting">
			<view class="ensure">
				<view @click="closeMoreSetting" class="title">更多设置<text class="iconfont icon-guanbi5"></text></view>
				<view class="list"
					style="height: auto;padding: 20rpx 0;display: flex;flex-direction: row;justify-content: space-between;">
					<view @click="moreSettingClick(item,index)" v-for="(item, index) in moreSettingInfoList"
						:key="index">
						<view
							style="padding: 10px 5px;text-align: center;border-radius: 5px;box-shadow: 1px 1px 5px #ddd;">
							<view style="align-items: center;justify-content: center;display: flex;">
								<u-icon style="justify-content: center;" :name="item.icon"
									:color="item.disable?'#bbb':bgColor" size="24" bold></u-icon>
							</view>
							
							<view style="margin-top: 5px;font-weight: bold;" :style="{color:item.disable?'#bbb':''}">
								{{item.name}}
							</view>
						</view>
					</view>
				</view>
				<view style="height: 50px;"></view>
			</view>
		</tui-drawer>
		<!-- 上下架选择仓库 弹窗 -->
		<tui-drawer mode="bottom" :visible="showUpDatePopup" @close="closeComuleDate">
			<view class="ensure">
				<view class="title"><text @click="closeComuleDate"
						class="iconfont icon-guanbi5"></text>选择下架该商品的售卖区域<text @click="ComuleDate"
						class="iconfontRight">确认</text></view>
				<view style="text-align: center;">
					{{addCheckData.name}}
				</view>
				<view class="list" style="height: auto;padding-top: 20rpx;">
					<checkbox-group class="checke_list" @change="comuleCheckboxChange">
						<label class="uni-list-cell uni-list-cell-pd checke_item"
							v-for="(ele, indexw) in addCheckboxList" :key="indexw">
							<view class="item_top"
								style="margin-bottom: 32rpx;border-bottom: 1px solid #eee;justify-content: space-between;display: flex;padding-bottom: 20rpx;">
								<view class="item_img">
									{{ele.name}}
								</view>
								<checkbox :value="ele.operateCityId.toString()" :iconColor="bgColor" :color="bgColor"
									class="round-checkbox"/>
							</view>
						</label>
					</checkbox-group>
					<view style="height: 50px;"></view>
				</view>
			</view>
		</tui-drawer>

	<!-- 	<u-picker :defaultIndex="timeTypeIndex" :show="timeTypeShow" :columns="timeTypeColumns"
			:closeOnClickOverlay="true" @confirm="timeTypeConfirm" @close="timeTypeShow = false"
			@cancel="timeTypeShow = false" keyName="label">
		</u-picker> -->
		<!-- -----组件----- -->
		<u-modal style="position: absolute;" :content="showInfoModalInfos[showInfoModalIndex]"
			:show="showInfoModalVision" showCancelButton buttonReverse @confirm="showInfoModalConfirm"
			@cancel="() => showInfoModalVision = false"></u-modal>
	</view>
</template>

<script>
	import {
		restoreApi,
		productDeleteApi,
		productDeleteSkuApi,
		putOnShellApi,
		offShellApi,
		productHeadersApi,
	} from '@/api/product.js'
	import swiperPageProduct from "../components/nvue-swiper-page-product.nvue"
	import tabBar from '../components/tab-bar.vue';
	import tuiDrawer from '@/components/tui-drawer/index.vue';
	import {
		setThemeColor
	} from '@/utils/setTheme.js'
	import animationType from '@/utils/animationType.js'
	let app = getApp();
	export default {
		components: {
			swiperPageProduct,
			tabBar,
			tuiDrawer
		},
		data() {
			return {
				bgColor: "#ffffff",
				theme: app.globalData.theme,
				keyword: "", //搜索商品
				tabHeaderLoading: true,
				tabList: [],
				currentIndex: 0,
				moreSettingDrawer: false, //更多设置弹窗
				moreSettingInfoList: [{
						name: "添加规格",
						icon: "plus-circle",
						disable: false,
					},
					{
						name: "修改图文",
						icon: "photo",
						disable: false,
					},
					{
						name: "修改信息",
						icon: "edit-pen",
						disable: false,
					},
					{
						name: "加入回收站",
						icon: "trash",
						disable: false,
					},
				],
				selectedProdct: null, //选择的商品
				showInfoModalVision: false, //多功能确认事件
				showInfoModalIndex: 0,
				showInfoModalInfos: [
					"该商品正在出售中，是否确认进行编辑？",
					"确定将该商品加入回收站吗？",
					"确认恢复商品吗？"
				],
				//-- 上下架选择
				addCheckData: {},
				addCheckboxList: [],
				showUpDatePopup: false,
				//---
				timeTypeIndex: [0], //默认选择
				timeTypeShow: false, //发票类型选择
				timeTypeColumns: 
					[{
							label: '正序',
							id: 0
						},
						{
							label: '倒序',
							id: 1
						}
					]
				,
				timeTypesIndex:0,
				checkBoxValue:[],
			};
		},
		onLoad() {
			this.bgColor = setThemeColor();
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.bgColor,
			});
			this.tabList = [{
					id: "tab11",
					title: "出售中",
					name: "",
					type: 1,
					count: 0,
				},
				{
					id: "tab12",
					title: "仓库中",
					name: "",
					type: 2,
					count: 0,
				},
				{
					id: "tab13",
					title: "已售罄",
					name: "",
					type: 3,
					count: 0,
				},
				{
					id: "tab14",
					title: "警戒库存",
					name: "",
					type: 4,
					count: 0,
				},
				{
					id: "tab15",
					title: "审核中",
					name: "",
					type: 5,
					count: 0,
				},
				{
					id: "tab16",
					title: "未通过",
					name: "",
					type: 6,
					count: 0,
				},
				{
					id: "tab17",
					title: "回收站",
					name: "",
					type: 7,
					count: 0,
				}
			];
			//加载 tabs 类型 商品数量 
			this.getProductTabsHeaders();
		},
		created() {
			uni.$on('shopMessageoTherFun', this.getProductTabsHeaders);
		},
		destroyed() {
			uni.$off('shopMessageoTherFun', this.getProductTabsHeaders);
		},
		onShow() {
			//初始化页面
			if (this.$refs.tab) {
				for (let item of this.$refs.tab) {
					item.getProductList();
				}
			};
			this.getProductTabsHeaders();
		},
		methods: {
			// 触底事件 onReachBottom 加载更多数据
			scrolltolowerFn() {
				this.$refs.tab[this.currentIndex].scrolltolowerFn();
			},
			toAddProduct(item) {
				this.goPage(`/pages/product/saveProduct/saveProduct?type=add`);
			},
			toDetails(item) {
				this.goPage(`/pages/product/productDetails/productDetails?id=${item.productId}`);
			},
			goPage(url) {
				uni.navigateTo({
					animationType: animationType.type,
					animationDuration: animationType.duration,
					url
				})
			},
			// 时间类型选择
			// timeTypeConfirm(ele) {
			// 	let valueType = ele.value[0].id;
			// 	this.timeTypeShow = false;
			// 	this.$refs.tab[this.currentIndex].timeTypeProduct(valueType);
			// },
			timeTypeConfirm(ele) {
				let i = ele.detail.value;
				let valueType = this.timeTypeColumns[i].id;
				this.timeTypeShow = false;
				this.$refs.tab[this.currentIndex].timeTypeProduct(valueType);
			},
			// 取消选择
			cancelPicker(){
				this.timeTypeShow = false;
			},
			/** 
			 * 上下架弹窗
			 */
			openUpDataSetting(item) {
				this.addCheckData = item;
				
				this.addCheckboxList = item.showOrNot;
				this.showUpDatePopup = true;
			},
			/** 
			 * 上下架，关闭选择仓库
			 */
			closeComuleDate() {
				this.showUpDatePopup = false;
				this.addCheckboxList = []; //清空
			},
			comuleCheckboxChange(value) {
				// this.checkBoxValue = value;
				
				let checkValue = value.detail.value;
				this.checkBoxValue = checkValue;
			},
			// 售卖区域确认弹窗
			ComuleDate() {
				if(!this.checkBoxValue.length){
					return uni.$u.toast('请选择售卖区域');
				};
				let comuleData = {};
				comuleData.skuId = this.addCheckData.skuId;
				comuleData.productId = this.addCheckData.productId;
				comuleData.operateCityIds = this.checkBoxValue;
				let item = this.addCheckData;
				this.$refs.tab[this.currentIndex].upOfDown(item, comuleData);
				this.showUpDatePopup = false;
			},
			//关闭更多
			closeMoreSetting() {
				this.moreSettingDrawer = false;
			},
			//打开更多
			openMoreSetting(item) {
				this.selectedProdct = item;
				// 状态为仓库中的才可以加入回收站
				let isDisable = this.tabList[this.currentIndex].type != 2
				this.$set(this.moreSettingInfoList[3], 'disable', isDisable);
				this.moreSettingDrawer = true;
			},
			//更多点击事件
			moreSettingClick(item, index) {
				if (item.disable) {
					// console.log("已禁用");
					return;
				}
				let product = this.selectedProdct;
				let that = this;
				switch (index) {
					case 0: //添加规格
						//检查是否出售中商品
						// if (product.showOrNot[0].status == 1) {
						// 	//提示下架后在编辑
						// 	this.showInfoModalByIndex(0);
						// 	return;
						// }
						this.moreSettingDrawer = false;
						//跳转修改商品界面
						this.toUpdate(product.productId,'add');
						break;
					case 1: //修改图文
						//跳转修改商品界面
						this.toModifyImage(product.productId);
						break;
					case 2: //修改信息
						//检查是否出售中商品
						// if (product.showOrNot[0].status == 1) {
						// 	//提示下架后在编辑
						// 	this.showInfoModalByIndex(0);
						// 	return;
						// }
						this.moreSettingDrawer = false;
						//跳转修改商品界面
						this.toUpdate(product.productId,'edit');
						break;
					case 3: //加入回收站
						this.showInfoModalByIndex(1);
						break;
				}
			},
			//显示指定模态框
			showInfoModalByIndex(index) {
				this.showInfoModalIndex = index;
				this.showInfoModalVision = true;
			},
			showInfoModalByParam(param) {
				this.selectedProdct = param.product;
				this.showInfoModalByIndex(param.index);
			},
			//确认下架 并 跳转修改商品
			showInfoModalConfirm() {
				let id = this.selectedProdct.productId;
				let skuId = this.selectedProdct.skuId;
				let uniqueId = this.selectedProdct.uniqueId;
				let that = this;
				switch (this.showInfoModalIndex) {
					case 0: //下架后编辑商品
						// this.upOfDown(id, false, () => {
						that.moreSettingDrawer = false;
						that.refresh(); //刷新商品
						that.toUpdate(id); //跳转页面
						// });
						break;
					case 1: //加入商品到回收站
						this.deleteProduct(id,skuId,uniqueId, () => {
							that.moreSettingDrawer = false;
							that.refresh(); //刷新商品
						});
						break;
					case 2: //回收站恢复商品
						this.restoreProduct(id, () => {
							that.refresh(); //刷新商品
						});
						break;
				}
				that.showInfoModalVision = false;
			},

			//搜索商品
			searchProduct(value) {
				//调用当前选择的类型页面查询方法
				this.$refs.tab[this.currentIndex].searchProduct(value);
			},
			//子组件请求刷新 header 和 商品列表
			async refresh() {
				await this.getProductTabsHeaders();
				for (let t of this.$refs.tab) {
					t.initData();
				}
			},
			//跳转修改商品界面
			toUpdate(id,type) {
				this.goPage(`/pages/product/saveProduct/saveProduct?id=${id}&type=${type}`);
			},
			// 跳转修改图文界面
			toModifyImage(id) {
				this.goPage(`/pages/product/modifyImage/modifyImage?type=update&id=${id}`);
			},
			//api service ----------------------------------------
			//加载 tabs 类型下商品数量 
			getProductTabsHeaders() {
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				this.tabHeaderLoading = true;
				let that = this;
				productHeadersApi().then(res => {
					let data = res.data;
					for (var i = 0; i < data.length; i++) {
						let tab = that.tabList[i];
						let dataItem = data[i];
						tab.count = dataItem.count;
						tab.name = tab.title + "(" + dataItem.count + ")";
					}
					that.tabHeaderLoading = false;
					uni.hideLoading();
				}).catch(err => {
					console.log("productHeadersApi error", err)
					uni.hideLoading();
				});

			},
			// // 商品上下架设置
			// upOfDown(id, isUp, successFun) {
			// 	let api = isUp ? putOnShellApi : offShellApi;
			// 	let that = this;
			// 	uni.showLoading({
			// 		title: '加载中',
			// 		mask: true
			// 	});
			// 	api(id).then(res => {
			// 		if (res.code == 200) {
			// 			if (successFun) {
			// 				successFun();
			// 			}
			// 		} else {
			// 			uni.$u.toast('操作失败');
			// 		}
			// 		uni.hideLoading();
			// 	}).catch(err => {
			// 		console.log("upOfDown error", err);
			// 		uni.hideLoading();
			// 	});
			// },
			//加入回收站
			deleteProduct(id,skuId,uniqueId, successFun) {
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				productDeleteSkuApi({
					productId: id,
					skuId:skuId,
					uniqueId:uniqueId,
					type: "recycle"
				}).then(res => {
					if (res.code == 200) {
						if (successFun) {
							successFun();
						}
					} else {
						uni.$u.toast('操作失败');
					}
					uni.hideLoading();
				}).catch(err => {
					console.log("deleteProduct error", err);
					uni.hideLoading();
				});
			},
			//回收站恢复
			restoreProduct(productId, successFun) {
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				restoreApi(productId).then(res => {
					if (res.code == 200) {
						if (successFun) {
							successFun();
						}
					} else {
						uni.$u.toast('操作失败');
					}
					uni.hideLoading();
				}).catch(err => {
					console.log("restoreProduct error", err);
					uni.hideLoading();
				});
			}
		}

	}
</script>

<style lang="scss">
	/* #ifndef APP-PLUS */
	page {
		width: 100%;
		min-height: 100%;
		display: flex;
	}

	::v-deep .u-popup {
		flex: 0 !important;
	}

	.page {
		flex: 1;
	}

	/* #endif */
	.products {
		display: flex;
		flex: 1;
		flex-direction: column;
		overflow: hidden;
		// background-color: #ffffff;
		/* #ifdef MP-ALIPAY || MP-BAIDU */
		height: 100vh;
		/* #endif */
	}

	.bg_color {
		@include main_bg_color(theme);
	}

	.plain_bgColor {
		@include main_color(theme);
		@include main_bg_rgba_color(theme, 0.05);
		border: 1rpx solid;
	}

	.tab-view {
		display: flex;
		flex-direction: column;
		flex: 1;
	}

	.swiper-item {
		flex: 1;
		flex-direction: column;
	}

	.swiper-page {
		flex: 1;
		flex-direction: column;
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
	}

	.ensure {
		width: 100%;
		background-color: #fff;
		padding-bottom: 22rpx;
		padding-bottom: calc(22rpx+ constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
		padding-bottom: calc(22rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/

		.title {
			font-size: 32rpx;
			color: #282828;
			text-align: center;
			margin: 38rpx 0 36rpx 0;
			position: relative;

			.iconfont {
				position: absolute;
				left: 30rpx;
				top: 0;
				font-size: 36rpx;
			}

			.iconfontRight {
				position: absolute;
				right: 30rpx;
				top: 0;
				font-size: 36rpx;
			}
		}

		.list {
			height: 750rpx;
			margin: 0 30rpx;
			overflow-x: hidden;
			overflow-y: auto;

			.item {
				margin-bottom: 52rpx;

				.pictrue {
					width: 36rpx;
					height: 36rpx;
					border-radius: 50%;
					margin-right: 30rpx;

					/deep/image,
					.easy-loadimage,
					image,
					uni-image {
						width: 100%;
						height: 100%;
						border-radius: 50%;
					}
				}

				.text {
					width: 618rpx;
					color: #999999;
					font-size: 28rpx;

					.name {
						color: #333333;
						font-weight: bold;
						margin-bottom: 20rpx;
					}
				}
			}
		}

	}

	/deep/ .tui-drawer-container_bottom {
		border-radius: 16rpx 16rpx 0 0;
	}
</style>